<!--
  * 部门表单 弹窗
  *
  * @Author:    zhoujk
  * @Date:      2022-08-08 20:46:18
-->
<template>
  <a-modal v-model:open="visible" :title="form.id ? '编辑部门' : '添加部门'" @ok="handleOk" destroyOnClose>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-form-item label="上级部门" v-if="form.fDepartId !== '0000000000000'">
        <DepartTreeSelect width="100%" ref="parentDepartTreeSelect" v-model:value="form.fDepartId" />
      </a-form-item>

      <a-form-item label="部门名称" name="name">
        <a-input v-model:value.trim="form.name" placeholder="请输入部门名称" />
      </a-form-item>

      <a-form-item label="业务" name="businessFlag">
        <a-radio-group v-model:value="form.businessFlag">
          <a-radio :value="true">是</a-radio>
          <a-radio :value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="部门负责人" name="managerIds">
        <CustomSelect
          v-model:value="form.managerIds"
          :api="userApi.page"
          :queryParams="userParams"
          queryParamKey="nameLeftLike"
          mode="multiple"
          :response-adapter="filterParams"
          valueField="id"
          labelField="name,no"
          width="100%"
        />
      </a-form-item>

      <a-form-item label="部门描述" name="desc">
        <a-textarea style="width: 100%" v-model:value="form.desc" placeholder="请输入部门描述" :auto-size="{ minRows: 4, maxRows: 4 }" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
  import message from 'ant-design-vue/lib/message'
  import { reactive, ref } from 'vue'
  import { departApi } from '/src/api/system/b-agent/depart-api'
  import DepartTreeSelect from '/src/components/system/b-operation/depart-tree-select/index.vue'
  import { smartSentry } from '/src/lib/smart-sentry'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { ZZB_ENABLE_STATUS_ENUM } from '/src/constants/system/system-const.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { userApi } from '/@/api/system/b-agent/user-api.js'
  import { PAGE_SIZE } from '/@/constants/common-const.js'

  // ----------------------- 对外暴漏 ---------------------

  defineExpose({
    showModal,
  })

  // ----------------------- modal 的显示与隐藏 ---------------------
  const emits = defineEmits(['refresh'])

  const visible = ref(false)

  function showModal(data) {
    visible.value = true
    updateFormData(data)
  }

  function closeModal() {
    visible.value = false
    resetFormData()
  }

  // ----------------------- form 表单操作 ---------------------
  const formRef = ref()
  const parentDepartTreeSelect = ref()
  const defaultDepartForm = {
    id: undefined,
    fDepartId: undefined,
    name: undefined,
    status: ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value,
    managerIds: [], //部门负责人
    businessFlag: false,
    desc: undefined,
  }
  const userSelect = ref()

  let form = reactive({
    defaultDepartForm,
  })
  // 表单校验规则
  const rules = {
    name: [
      { required: true, message: '部门名称不能为空' },
      { max: 50, message: '部门名称不能大于20个字符', trigger: 'blur' },
    ],
    managerIds: [{ required: true, message: '部门负责人不能为空' }],
  }

  // 更新表单数据
  function updateFormData(data) {
    data.managerIds = data?.managers?.map((item) => item.id)
    Object.assign(form, defaultDepartForm)
    if (data) {
      Object.assign(form, data)
    }
    visible.value = true
  }

  // 重置表单数据
  function resetFormData() {
    Object.assign(form, defaultDepartForm)
  }

  async function handleOk() {
    try {
      await formRef.value.validate()
      if (form.id) {
        update()
      } else {
        insert()
      }
    } catch (error) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // ----------------------- form 表单  ajax 操作 ---------------------
  //添加部门ajax请求
  async function insert() {
    SmartLoading.show()
    try {
      await departApi.insert(form)
      emits('refresh')
      closeModal()
    } catch (error) {
      smartSentry.captureError(error)
    } finally {
      SmartLoading.hide()
    }
  }

  //更新部门ajax请求
  async function update() {
    SmartLoading.show()
    try {
      if (form.fDepartId === form.id) {
        message.warning('上级菜单不能为自己')
        return
      }
      await departApi.update(form)
      emits('refresh')
      closeModal()
    } catch (error) {
      smartSentry.captureError(error)
    } finally {
      SmartLoading.hide()
    }
  }

  const filterParams = (val) => {
    val.data?.forEach((element, index, arr) => {
      arr[index].disabled = element.status === ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
    })

    return val
  }
  const userParams = reactive({
    // status: ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value,
    showRoleFlag: false,
  })
</script>
